package com.dyh.quickdemo.demos.dfun;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;

/*
@Author=Joey Wheeler
@Date=2020/10/20 13:46
*/
@Setter@Getter
public class DFunction<T,R> implements Function<T,R> {

    public List<Function<T,R> > interceptors;
    /*没有after的存在必要*/
    public Function<T,R> core;

    public DFunction (Function<T,R> core){
        this.core = core;
    }

    public DFunction<T,R> addInterceptor(Function<T,R> interceptor){
        if (this.interceptors == null)
            this.interceptors = new LinkedList<>();
        this.interceptors.add(interceptor);
        return this;
    }

    @Override
    public R apply(T t) {

        R r = null;
        for (Function<T, R> interceptor : interceptors) {
            r = interceptor.apply(t);
            if (r!=null)//拦截到
                return r;
        }
        r = core.apply(t);
        return r;
    }

}
